import os
import sys
import copy
import logging

from command_parser.command_generate import GenCommand
from command_parser.ld_parse.ld_option_filter import LDFilter


class LDGenCommand(GenCommand):
    def __init__(self, context=None, cwd=""):
        super().__init__(context=context, cwd=cwd)
        self.filter = LDFilter(context=self.context)
    
      
    def ast_to_mpl(self, ast_path=""):
        if not ast_path:
            raise Exception("Lack of ast file when getting mpl path")
        
        md5_str = os.path.splitext(os.path.basename(ast_path))[0]
        mpl_path = os.path.join(self.context.MAPLE_DIR, md5_str + self.context.MAPLE_EXT)
        
        return mpl_path
    

    def generate_original_command(self, compiler="", options=[]):
        # we should convert the "-lxxx" to full path first
        self.filter.update_search_paths(options=options)
        self.filter.handle_orignal_options(cwd=self.cwd, options=options)
        
        return super(LDGenCommand, self).generate_original_command(compiler=compiler, options=options)
    
    
    def generate_maple_link_command(self, compiler="", input_options=[], output_option=None):
        
        if not compiler or not input_options or not output_option:
            raise Exception("It occurs faild when generate_maple_link_command")
        
        if self.context.IR_CAT_MODE:
            return self.get_maple_ir_cat_command(input_options, output_option)

        # it's output_file was replaced when replay the build process
        input_files = []
        for opt in input_options:
            if opt.keep:
                input_files.extend(opt.parameter)
        
        output_file = output_option.parameter[0]
        
        command_line = [compiler, "-wpaa"]
        for input_file in input_files:
            command_line.append(input_file)
        
        command_line.append("-o")
        command_line.append(output_file)
        command_line.append("--enable-variable-array")
        
        return command_line
    
    def get_maple_ir_cat_command(self, input_options=[], output_option=None):
        
        input_files = []
        
        for opt in input_options:
            if opt.keep:
                input_files.extend(opt.parameter)
        
        output_file = output_option.parameter[0]
        
        sub_cmd = "cat {} >> {}".format(' '.join(input_files), output_file)
        
        command = ["sh", "-c", sub_cmd]
        
        return command
            